//
//  WNLibraryVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/5.
//

import UIKit

let LibRecHeader = "LibRecReusableView"

class WNLibraryVC: WNBaseVC {
    
    lazy var searchView: WNSearchView = {
        let view = WNSearchView()
        view.searchType(0)
        return view
    }()
    
    lazy var libColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = (ScreenW-scaleWidth(100)*3-42)*0.5
        layout.itemSize = CGSize(width: scaleWidth(100), height: scaleWidth(144)+42)
        layout.sectionInset = .init(top: 20, left: 20, bottom: 20, right: 20)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .white
        col.delegate = self
        col.dataSource = self
        col.register(LibColCell.self, forCellWithReuseIdentifier: LibColCell.identifier)
        col.register(LibRecReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: LibRecHeader)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .library, imageStr: .library, tapBlock: { [weak self] in
            self?.getLibRequest()
        })
        col.isHidden = true
        return col
    }()
    
    var libLastModel: BookDetailModel? {
        didSet {
            if let m = libLastModel {
                showTabLast(self, m)
            }
        }
    }
    
    var likeArr = [BookDetailModel]()
    
    var libArr = [BookDetailModel]()
    
    var selIndexArr = [Int]()
          
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        dataRequest()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        wn_hidNavView()
        view.addSubview(searchView)
        view.addSubview(libColView)
        searchView.snp.makeConstraints { (make) in
            make.top.equalTo(StatusBarHeight)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        libColView.snp.makeConstraints { make in
            make.top.equalTo(searchView.snp.bottom)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarTotalHeight)
        }
    }
    
    override func dataConfig() {
        pageName = "書架"
        getLibRequest()
        getLikeRequest()
        getTabLastRequest()
        libColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.getLibRequest()
            self?.getLikeRequest()
        })
    }

    override func handleNoti() {
        NotificationCenter.default.addObserver(forName: WNNotiName.loginNoti, object: nil, queue: nil) { [weak self] not in
            self?.dataConfig()
        }
        NotificationCenter.default.addObserver(forName: WNNotiName.collectNoti, object: nil, queue: nil) { [weak self] not in
            if let favorite = not.userInfo?["favorite"] as? Bool, let bookId = not.userInfo?["bookId"] as? String {
                if favorite {
                    self?.getLibRequest()
                }else {
                    if let arr = self?.libArr, arr.first(where: {$0.bookId == bookId }) != nil {
                        var item = 0
                        for (i, v) in arr.enumerated() {
                            if v.bookId == bookId {
                                item = i
                            }
                        }
                        self?.libArr.remove(at: item)
                        self?.libColView.reloadData()
                    }
                }
            }
        }
        NotificationCenter.default.addObserver(forName: WNNotiName.collectArrNoti, object: nil, queue: nil) { [weak self] not in
            if let bookIds = not.userInfo?["bookIds"] as? [String], let arr = self?.libArr {
                var index = [Int]()
                for (i, v) in arr.enumerated() {
                    if bookIds.wn_contains(obj: v.bookId) {
                        index.append(i)
                    }
                }
                if index.count != 0 {
                    self?.libArr.removeAt(indexes: index)
                    self?.libColView.reloadData()
                }
            }
        }
    }
}

extension WNLibraryVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        libArr.count+1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: LibColCell.identifier, for: indexPath) as! LibColCell
        if indexPath.item < libArr.count {
            cell.model = libArr[indexPath.item]
        }else {
            cell.model = nil
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item < libArr.count {
            wn_pushBookVC(libArr[indexPath.item].bookId ?? "")
        }else {
            tabBarController?.selectedIndex = 1
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let recView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: LibRecHeader, for: indexPath) as? LibRecReusableView
            recView?.libArr = likeArr
            return recView!
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return .init(width: ScreenW, height: scaleWidth(88)+86)
    }
}

extension WNLibraryVC {
    
    func getLibRequest() {
        provider_setting.rx.request(.collectList(page, 9))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.libColView.isHidden = false
                self?.libColView.ly_emptyView.imageStr = EmptyImage.library.rawValue
                self?.libColView.ly_emptyView.detailStr = EmptyDesc.library.rawValue
                self?.libColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.libColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.libColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.libColView.ly_emptyView.btnTitleStr = "點擊刷新"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.libColView.mj_header?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.libArr.removeAll()
                    self?.libColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 8
                    self?.libArr += arr
                }else {
                    self?.libColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.libColView.reloadData()
                self?.libColView.mj_header?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("檢查網路連線")
                self?.libColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.libColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.libColView.ly_emptyView.btnTitleStr = "點擊刷新"
                self?.libColView.mj_header?.endRefreshing()
                self?.libColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
    
    func getLikeRequest() {
        provider_discover.rx.request(.guesslike(1))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                if let arr = model.data {
                    self?.likeArr = arr
                    self?.libColView.reloadData()
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    func getTabLastRequest() {
        provider_user.rx.request(.getLastBook)
            .asObservable().mapModel(BaseModel<BookDetailModel>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    return
                }
                self?.libLastModel = nil
                if let data = model.data {
                    self?.libLastModel = data
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    func dataRequest() {
        let group = DispatchGroup()
        group.enter()
        provider_user.rx.request(.checkTicket)
            .asObservable().mapModel(BaseModel<[TicketModel]>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                saveHasCheck(true)
                if let arr = model.data, arr.filter({$0.status == 2}).count > 0 {
                    saveHasCheck(false)
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.enter()
        provider_login.rx.request(.checkUser)
            .asObservable().mapModel(BaseModel<UserDetailModel>.self)
            .subscribe(onNext: { (model) in
                guard model.code == 0 else { return group.leave() }
                if let data = model.data {
                    saveUser(user: data)
                    setKeyUserId(data.userId ?? "")
                    WNSingleData.shared.userGold = data.gold
                }
                group.leave()
            }, onError: { (error) in
                group.leave()
            }).disposed(by: rx.disposeBag)
        group.notify(queue: DispatchQueue.main) { [weak self] in
            self?.searchView.readImage.isHidden = getHasCheck()
        }
    }
}
